package com.lam.common.components.easyexcel.imp;

import java.io.InputStream;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.handler.WriteHandler;
import com.lam.common.components.easyexcel.handlers.DropDownWriteHandler;
import com.lam.common.components.easyexcel.handlers.HeadRowCommentWriteHandler;
import com.lam.common.components.easyexcel.imp.listener.BaseListener;
import com.lam.common.components.parameter.ParameterConfigUtil;
import com.lam.common.exception.BusinessException;
import com.lam.common.exception.UploadException;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.validate.ValidConvert;

public class ImportUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(ImportUtil.class);
	
	private static final int DEFAULT_UPLOAD_EXCEL_MAX_SIZE = 4;
	
	public static WriteHandler getDropDownWriteHandler(Class<?> importDataClazz, Class<?> ... groups) {
		Map<Integer, String[]> dropDownData = ValidConvert.getDropDownData(importDataClazz, groups);
		if(CollectionUtil.isEmpty(dropDownData)) {
			return null;
		}
		return new DropDownWriteHandler(dropDownData);
	}
	
	public static WriteHandler getHeadRowCommentWriteHandler(Class<?> importDataClazz, Class<?> entityClazz, Class<?> ... groups) {
		Map<Integer, String> commentData = ValidConvert.getCommentData(importDataClazz, entityClazz, groups);
		if(CollectionUtil.isEmpty(commentData)) {
			return null;
		}
		return new HeadRowCommentWriteHandler(commentData);
	}
	
	/**
	 * 导入数据
	 * @param <T> 导入数据的对象类
	 * @param businessName 业务名称
	 * @param file web上传的文件对象
	 * @param readListener 解析上传文件的监听器
	 * @throws UploadException 
	 */
	public static <T, R> void importData(String businessName, MultipartFile file, BaseListener<T, R> readListener) {
		
		if(file == null) {
			logger.error(businessName + "导入异常！上传文件对象为空！");
            throw new UploadException(businessName + "导入异常，没有文件对象！");
		}
        try (InputStream is = file.getInputStream()) {
        	int max = ParameterConfigUtil.getInteger("upload.excel.max.size", DEFAULT_UPLOAD_EXCEL_MAX_SIZE);
            int a = is.available();
            if (a > max * 1024 * 1024) {
            	logger.error("Excel导入失败, 单次上传文件超过限制, act:{}B, max:{}M ！", a, max);
            	throw new BusinessException(businessName+"导入失败，单个文件大小不能超过" + max + "M");
            }
            
            EasyExcel.read(is, readListener.getImportDataClazz(), readListener).sheet().doRead();
            logger.info("{}导入完成! batchNo:{} ", businessName, readListener.getBatchNo());
        } catch (Exception e) {
            logger.error(businessName + "导入异常！batchNo: " + readListener.getBatchNo(), e);
            throw new UploadException(businessName + "导入异常！");
        }
	}

}
